package com.zeek.car90s;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.mediation.admob.AdMobAdapter;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.game.UMGameAgent;
import com.zeek.car90s.adapter.GameAdapter;
import com.zeek.car90s.util.DbHelper;
import com.zeek.car90s.util.MediaPlayerUtils;
import com.zeek.car90s.util.RandomArray;
import com.zeek.car90s.util.SoundPoolUtils;
import com.zeek.car90s.util.StringUtils;
import com.zeek.car90s.util.Tools;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class GameActivity extends AppCompatActivity implements View.OnClickListener, RewardedVideoAdListener {

    private GridView gridview;
    private List<String> datalist;//所以备选文字的集合
    private RandomArray rand;
    //    private String correctAnswers[] = {
//            "周杰伦", "曹操", "车", "水", "人", "弓", "耳", "龟", "九", "齿",
//            "日", "木", "心", "月", "老", "龙", "马", "门", "美", "米",
//            "鬼", "明", "目", "内", "中", "衣", "羊", "小", "下", "巫",
//            "舞", "土", "王", "文", "矢", "肉", "入", "犬", "千", "女",
//            "朋", "牛", "男", "皿", "品", "鸟", "鹿", "口", "牢", "京",
//            "邦", "宝", "丹", "帝", "多", "封", "父", "壶", "鸡", "后",
//            "妹", "禾", "官", "买", "鲁", "明", "母", "丘", "雀", "如",
//            "商", "舌", "申", "尸", "唐", "食", "生", "室", "首", "田",
//            "万", "我", "习", "武", "乡", "新", "须", "易", "饮", "正",
//            "异", "微", "射", "秋", "齐", "牧", "旅", "酒", "黄", "果",
//    };
    private ArrayList<String> correctAnswers = new ArrayList<>();//存放所有答案
    private ArrayList<String> topics = new ArrayList<>();//存放所有问题
    private int j, answerLength;
    private List<Map<String, Object>> list;
    private SharedPreferences sp;
    private Button answerButtonOne, answerButtonTwo, answerButtonThree, answerButtonFour,
            answerButtonFive, answerButtonSix, answerButtonSeven, answerButtonEight, answerButtonNine, answerButtonTen;
    private Button answerButtonOne2, answerButtonTwo2, answerButtonThree2, answerButtonFour2,
            answerButtonFive2, answerButtonSix2, answerButtonSeven2, answerButtonEight2, answerButtonNine2, answerButtonTen2;
    private String answerone = null, answertwo = null, answerthree = null;
    private String[] answers;//答案框上村粗的数据
    private View[] views;//大小和答案框一样，存放的确是gridview里面的view
    private ArrayList<Button> answerButtons, answerButtons2;
    private TextView tvGameLevel;
    private Button btnBack, btnCoin;
    private ImageView imageShowAnswer, imageVideo;
    private RelativeLayout bannerContainer;
    private LinearLayout llTwoButtons;
    //    private AdsMogoLayout adsMogoView;
    private SQLiteDatabase db;
    private ArrayList<Integer> coinIdList = new ArrayList<>();//已经得到了金币的

    private ImageView imageViewGame;//显示图片
    private TextView tvTopic;//显示文字
    private int answerWordCount;//答案里的单词数量，决定答案显示一排还是两排
    private String[] answers2;//两个单词时的答案组

    private boolean mIsRewardedVideoLoading;
    private final Object mLock = new Object();//视屏广告锁


    //定义分享平台
//    final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[]
//            {
//                    SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA,
//                    SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE,
//            };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Constants.TYPE == 3) {
            setContentView(R.layout.activity_game_mix);
        } else {
            setContentView(R.layout.activity_game);
        }

        gridview = (GridView) findViewById(R.id.game_gridView1);

        initButtons();

        tvGameLevel = (TextView) findViewById(R.id.game_level);
        tvTopic = (TextView) findViewById(R.id.game_topic);
        imageViewGame = (ImageView) findViewById(R.id.game_image);
        llTwoButtons = (LinearLayout) findViewById(R.id.ll_two_buttons);
        imageShowAnswer = (ImageView) findViewById(R.id.game_show_answer);
        imageShowAnswer.setOnClickListener(this);
        imageVideo = (ImageView) findViewById(R.id.game_video);
        imageVideo.setOnClickListener(this);
        if(Constants.rewardedVideoAd.isLoaded()){
            imageVideo.setVisibility(View.VISIBLE);
        }else {
            imageVideo.setVisibility(View.INVISIBLE);
            loadRewardedVideoAd();
        }

        //展示banner
        AdView mAdView = (AdView) findViewById(R.id.adView_bottom);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        //初始化视频激励
//        Constants.rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
        Constants.rewardedVideoAd.setRewardedVideoAdListener(this);
        if (!Constants.rewardedVideoAd.isLoaded()) {
            loadRewardedVideoAd();
        }

        sp = getSharedPreferences(Constants.SHARED_PREFERENCE_PREFIX, Context.MODE_PRIVATE);

        initDatabase();

//        Constants.TOTAL_COIN = sp.getInt(Constants.COIN_PREFIX, 0);
        Constants.MAX_UNLOCK_LEVEL = sp.getInt(Constants.MAX_LEVEL_PREFIX, 0);
        Constants.CURRENT_LEVEL = sp.getInt(Constants.CURRENT_LEVEL_PREFIX, 0);
        Constants.MAX_CON_ID = sp.getInt(Constants.MAX_COIN_ID_PREFIX, 0);
        btnCoin = (Button) findViewById(R.id.tv_game_coin);
        btnCoin.setText(Constants.TOTAL_COIN + "");
        btnCoin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayerUtils.playNotification(1);
                startActivity(new Intent(GameActivity.this, EarnCoinsActivity.class));
                MobclickAgent.onEvent(GameActivity.this, "earn_coin_from_add");
            }
        });
        findViewById(R.id.iv_add_coins).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayerUtils.playNotification(1);
                startActivity(new Intent(GameActivity.this, EarnCoinsActivity.class));
                MobclickAgent.onEvent(GameActivity.this, "earn_coin_from_add");
            }
        });

        //返回到MapList
        findViewById(R.id.game_level).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayerUtils.playNotification(1);
                startActivity(new Intent(GameActivity.this, MapActivity.class));
            }
        });

        //初始化已经领过金币的关卡
        for (int i = 0; i < Constants.MAX_CON_ID; i++) {
            coinIdList.add(i);
        }

        btnBack = (Button) findViewById(R.id.button_back);
        btnBack.setOnClickListener(this);
        btnBack.setText("Home");

        rand = new RandomArray();
        datalist = new ArrayList<String>();

        //初始化分享平台
        initSharePlatform();

        startGame();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshCoin();

        Constants.rewardedVideoAd.setRewardedVideoAdListener(this);
        if (!Constants.rewardedVideoAd.isLoaded()) {
            loadRewardedVideoAd();
        } else {
            imageVideo.setVisibility(View.VISIBLE);
        }
    }

    private void startGame() {

        //每3关展示一次插屏
        if (Constants.CURRENT_LEVEL > 0 && Constants.CURRENT_LEVEL % 3 == 0) {
//            if (Constants.mInterstitialAd.isLoaded()) {
//                Constants.mInterstitialAd.show();
//            }
        }

        for (Button button : answerButtons) {
            button.setOnClickListener(this);
            button.setText("");
            button.setVisibility(View.GONE);
        }

        for (Button button : answerButtons2) {
            button.setOnClickListener(this);
            button.setText("");
            button.setVisibility(View.GONE);
        }

        Constants.IS_ADD_COIN = false;
        answers2 = correctAnswers.get(Constants.CURRENT_LEVEL).split(" ");
        answerWordCount = answers2.length;

        if (answerWordCount == 1) {
            //根据正确答案显示格子数
            answerLength = correctAnswers.get(Constants.CURRENT_LEVEL).length();
            if (answerLength > answerButtons.size()) {
                nextLevel();
            }
            answers = new String[answerLength];
            views = new View[answerLength];
            for (int i = 0; i < answerLength; i++) {
                answerButtons.get(i).setVisibility(View.VISIBLE);
            }
        } else if (answerWordCount == 2) {//答案有两个单词，显示双行
            //显示两行答案格子
            answerLength = correctAnswers.get(Constants.CURRENT_LEVEL).replace(" ", "").length();
            if (answers2[0].length() > answerButtons.size() || answers2[1].length() > answerButtons2.size()) {
                nextLevel();
            }
            answers = new String[answerLength];
            views = new View[answerLength];
            for (int i = 0; i < answers2[0].length(); i++) {
                answerButtons.get(i).setVisibility(View.VISIBLE);
            }
            for (int i = 0; i < answers2[1].length(); i++) {
                answerButtons2.get(i).setVisibility(View.VISIBLE);
            }
        } else if (answerWordCount == 3) {//有三行的时候中间的字母和第13行较少的出现在一起
//            answerLength = correctAnswers.get(Constants.CURRENT_LEVEL).replace(" ", "").length();
//            answers = new String[answerLength];
//            views = new View[answerLength];
//            if (answers2[0].length() < answers2[2].length()) {
//                //第一个单词比较短，一二个单词放一行
//                if (answers2[0].length() + answers2[1].length() > answerButtons.size() - 1) {
//                    nextLevel();
//                }
//                for (int i = 0; i < answers2[0].length() + answers2[1].length() + 1; i++) {
//                    if (i == answers2[0].length()) {
//                        answerButtons.get(i).setVisibility(View.INVISIBLE);
//                    } else {
//                        answerButtons.get(i).setVisibility(View.VISIBLE);
//                    }
//                }
//                for (int i = 0; i < answers2[2].length(); i++) {
//                    answerButtons2.get(i).setVisibility(View.VISIBLE);
//                }
//            }else {
//                if (answers2[2].length() + answers2[1].length() > answerButtons.size() - 1) {
//                    nextLevel();
//                }
//                for (int i = 0; i < answers2[0].length(); i++) {
//                    answerButtons.get(i).setVisibility(View.VISIBLE);
//                }
//                for (int i = 0; i < answers2[1].length() + answers2[2].length() + 1; i++) {
//                    if (i == answers2[1].length()) {
//                        answerButtons2.get(i).setVisibility(View.INVISIBLE);
//                    } else {
//                        answerButtons2.get(i).setVisibility(View.VISIBLE);
//                    }
//                }
//            }
        }

        tvGameLevel.setText(Constants.CURRENT_LEVEL + 1 + "");

        imageViewGame.setVisibility(View.GONE);
        tvTopic.setVisibility(View.GONE);
        if (Constants.TYPE == 1) {//图片
            imageViewGame.setVisibility(View.VISIBLE);

            imageViewGame.setImageResource(getCurrentImageId());
        } else if (Constants.TYPE == 2) {//文字
            tvTopic.setVisibility(View.VISIBLE);

            tvTopic.setText(topics.get(Constants.CURRENT_LEVEL));
        } else if (Constants.TYPE == 3) {//图文混搭
            tvTopic.setVisibility(View.VISIBLE);
            imageViewGame.setVisibility(View.VISIBLE);

            tvTopic.setText(topics.get(Constants.CURRENT_LEVEL));
            imageViewGame.setImageResource(getCurrentImageId());
        }

        gridlist();
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MediaPlayerUtils.playNotification(1);
                for (int i = 0; i < answerLength; i++) {
                    if (StringUtils.isEmpty(answers[i])) {
                        if (answerWordCount == 2 && i >= answers2[0].length()) {//第二行
                            setAnswerText(i - answers2[0].length(), list.get(position).get("textview").toString(), true);
                        } else {//一行
                            setAnswerText(i, list.get(position).get("textview").toString(), false);
                        }
                        view.setVisibility(View.INVISIBLE);
                        views[i] = view;
                        break;
                    }
                }
            }
        });

        //友盟统计，进入关卡
        UMGameAgent.startLevel(Constants.CURRENT_LEVEL + "");
    }

    //获取当前关卡的图片
    public int getCurrentImageId() {
        return getResources().getIdentifier(getImageName(), "drawable", getApplicationInfo().packageName);
    }

    private String getImageName() {
        return "image_" + (Constants.CURRENT_LEVEL + 1);
    }

    //获取当前关卡的文字答案
    public String getCurrentAnswer() {
        return correctAnswers.get(Constants.CURRENT_LEVEL);
    }

    public String getCurrentTopic() {
        return topics.get(Constants.CURRENT_LEVEL);
    }

    //设置回答框的内容
    private void setAnswerText(int position, String content, boolean isSecondWord) {
        Button button = null;
        switch (position) {
            case 0:
                if (isSecondWord) {
                    button = answerButtonOne2;
                } else {
                    button = answerButtonOne;
                }
                break;
            case 1:
                if (isSecondWord) {
                    button = answerButtonTwo2;
                } else {
                    button = answerButtonTwo;
                }
                break;
            case 2:
                if (isSecondWord) {
                    button = answerButtonThree2;
                } else {
                    button = answerButtonThree;
                }
                break;
            case 3:
                if (isSecondWord) {
                    button = answerButtonFour2;
                } else {
                    button = answerButtonFour;
                }
                break;
            case 4:
                if (isSecondWord) {
                    button = answerButtonFive2;
                } else {
                    button = answerButtonFive;
                }
                break;
            case 5:
                if (isSecondWord) {
                    button = answerButtonSix2;
                } else {
                    button = answerButtonSix;
                }
                break;
            case 6:
                if (isSecondWord) {
                    button = answerButtonSeven2;
                } else {
                    button = answerButtonSeven;
                }
                break;
            case 7:
                if (isSecondWord) {
                    button = answerButtonEight2;
                } else {
                    button = answerButtonEight;
                }
                break;
            case 8:
                if (isSecondWord) {
                    button = answerButtonNine2;
                } else {
                    button = answerButtonNine;
                }
                break;
            case 9:
                if (isSecondWord) {
                    button = answerButtonTen2;
                } else {
                    button = answerButtonTen;
                }
                break;
        }
        button.setText(content);
        if (isSecondWord) {
            answers[position + answers2[0].length()] = content;
        } else {
            answers[position] = content;
        }

        String answer = getAnswer();
        if (answer.equals(correctAnswers.get(Constants.CURRENT_LEVEL).replace(" ", ""))) {
            MediaPlayerUtils.playNotification(2);
            //过关，字体颜色都变绿
            for (Button item : answerButtons) {
                item.setTextColor(Color.GREEN);
            }
            if (answerWordCount == 2) {
                for (Button item : answerButtons2) {
                    item.setTextColor(Color.GREEN);
                }
            }
            //友盟统计，过关
            UMGameAgent.finishLevel(Constants.CURRENT_LEVEL + "");
            JayneHatDialogFragment.show(this);

        } else {
            //字符填满的时候如果错误就播放错误音乐
            if (answer.length() == correctAnswers.get(Constants.CURRENT_LEVEL).replace(" ", "").length()) {
                MediaPlayerUtils.playNotification(3);
            }
            button.setTextColor(Color.RED);

//            button.setTextColor(Color.parseColor("#FFCC55"));
        }
    }

    private String getAnswer() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < answers.length && !StringUtils.isEmpty(answers[i]); i++) {
            builder.append(answers[i]);
        }
        return builder.toString();
    }

    public void nextLevel() {
//        //每过一关加5个金币
//        addCoin(5);

        Constants.CURRENT_LEVEL++;
        if (Constants.CURRENT_LEVEL > Constants.MAX_UNLOCK_LEVEL) {
            Constants.MAX_UNLOCK_LEVEL = Constants.CURRENT_LEVEL;
            SharedPreferences.Editor editor = sp.edit();
            editor.putInt(Constants.CURRENT_LEVEL_PREFIX, Constants.CURRENT_LEVEL);
            editor.putInt(Constants.MAX_LEVEL_PREFIX, Constants.MAX_UNLOCK_LEVEL);
            editor.commit();
        }
        startGame();
    }

    public void reStart() {
        startGame();
    }

    /**********************
     * GRIDVIEW适配数据
     *************************/
    public void gridlist() {
        InputStream inputStream = getResources().openRawResource(R.raw.b);
//        datalist = rand.listdateForEnglish(inputStream, correctAnswers.get(Constants.CURRENT_LEVEL) + getMixAnswer());
        datalist = rand.listdateForEnglish(inputStream, correctAnswers.get(Constants.CURRENT_LEVEL));
        setTwoButtonLocation(datalist.size());//设置两排按钮的位置

        list = new ArrayList<Map<String, Object>>();
        for (int z = 0; z < datalist.size(); z++) {
            Map<String, Object> listitem = new HashMap<String, Object>();
            listitem.put("textview", datalist.get(z).toString());
            list.add(listitem);
        }

        GameAdapter gameAdapter = new GameAdapter(datalist, this);
        gridview.setAdapter(gameAdapter);
//        SimpleAdapter simpleAdapter = new SimpleAdapter(this, list,
//                R.layout.game_gridview_item, new String[]{"textview"},
//                new int[]{R.id.tv_game_item});
//        gridview.setAdapter(simpleAdapter);
    }

    //根据显示的格子数量决定两排按钮相对下面位移多少
    private void setTwoButtonLocation(int count) {
        int dp;
        if (count > 14) {
            dp = 25;
            gridview.setNumColumns(count / 3);
        } else {
            dp = 45;
            //如果小于14个，那就显示对齐的两行
            gridview.setNumColumns(count / 2);
        }

        //px转dp
        Resources r = getResources();
        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) llTwoButtons.getLayoutParams();
        layoutParams.bottomMargin = px;
        llTwoButtons.setLayoutParams(layoutParams);
    }

    //处理点击答案按钮时候的事件
    @Override
    public void onClick(View v) {
        MediaPlayerUtils.playNotification(1);
        int selectedId = v.getId();
        if (selectedId == R.id.button_back) {
            finish();
            startActivity(new Intent(GameActivity.this, StartActivity.class));
        } else if (selectedId == R.id.game_show_answer) {
            UseCoinsFragment.show(this);
//            final int coinCost = getCoinCost();
//            DialogHelp.getConfirmDialog(GameActivity.this, coinCost + " coins to check the answer?", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    if (Constants.TOTAL_COIN < coinCost) {
//                        DialogHelp.getMessageDialog(GameActivity.this, "Sorry, your balance is not enough!").show();
//                    } else {
//                        for (int i = 0; i < answerLength; i++) {
//                            // setAnswerText(i, correctAnswers.get(Constants.CURRENT_LEVEL).substring(i, i + 1), false);
//                            if (answerWordCount == 2 && i >= answers2[0].length()) {//第二行
//                                setAnswerText(i - answers2[0].length(), correctAnswers.get(Constants.CURRENT_LEVEL).replace(" ", "").substring(i, i + 1), true);
//                            } else {//一行
//                                setAnswerText(i, correctAnswers.get(Constants.CURRENT_LEVEL).replace(" ", "").substring(i, i + 1), false);
//                            }
//                        }
//
////                        setAnswerText(0, correctAnswers.get(Constants.CURRENT_LEVEL));
//                        addCoin(-coinCost);
//
//                        Constants.CHECK_ANSWER_COUNT++;
//                        SharedPreferences.Editor editor = sp.edit();
//                        editor.putInt("check_answer_count", Constants.CHECK_ANSWER_COUNT);
//                        editor.apply();
//                    }
//                }
//            }).show();
//            UseCoinsFragment.show(this);
        } else if (selectedId == R.id.game_video) {//播放视频
            getWatchVideoCoins();
        }
//        else if (selectedId == R.id.game_share) {//分享到微信
////            mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE);
////            // 是否只有已登录用户才能打开分享选择页
////            mController.openShare(GameActivity.this, false);
//            shareToPlatforms();}
        else {
            //点击了答案栏的按钮
            int index = -1;
            boolean isClickSecondWord = false;
            for (int i = 0; i < answerButtons.size(); i++) {
                if (answerButtons.get(i).getId() == v.getId()) {
                    index = i;
                }
            }
            for (int i = 0; i < answerButtons2.size(); i++) {
                if (answerButtons2.get(i).getId() == v.getId()) {
                    index = i + answers2[0].length();
                    isClickSecondWord = true;
                }
            }
            //点击答案就把答案框上的文字清空
            if (index != -1) {
                if (isClickSecondWord) {
                    answerButtons2.get(index - answers2[0].length()).setText("");
                } else {
                    answerButtons.get(index).setText("");
                }
                answers[index] = "";
                if (views[index] != null) {
                    views[index].setVisibility(View.VISIBLE);
                }
            }
        }
    }

    //查看答案的金币花费
    private int getCoinCost() {
        return 30 + Constants.CHECK_ANSWER_COUNT * 30;
    }

    public void addCoin(int coinCount) {
        if (coinCount > 0) {//过关添加金币
            if (!coinIdList.contains(Constants.CURRENT_LEVEL)) {
                Constants.TOTAL_COIN += coinCount;

                Constants.MAX_CON_ID = Constants.CURRENT_LEVEL + 1;
//                btnCoin.setText(Constants.TOTAL_COIN + "");
//
                SharedPreferences.Editor editor = sp.edit();
//                editor.putInt(Constants.COIN_PREFIX, Constants.TOTAL_COIN);
                editor.putInt(Constants.MAX_COIN_ID_PREFIX, Constants.MAX_CON_ID);
                editor.commit();

                Constants.IS_ADD_COIN = true;

                SoundPoolUtils.play(1);
                coinIdList.add(Constants.CURRENT_LEVEL);
            }
        } else {//消费金币
            Constants.TOTAL_COIN += coinCount;
//            btnCoin.setText(Constants.TOTAL_COIN + "");

//            SharedPreferences.Editor editor = sp.edit();
//            editor.putInt(Constants.COIN_PREFIX, Constants.TOTAL_COIN);
//            editor.commit();

        }
        refreshCoin();
    }

    private void refreshCoin() {
        btnCoin.setText(Constants.TOTAL_COIN + "");

        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(Constants.COIN_PREFIX, Constants.TOTAL_COIN);
        editor.commit();

        if (Constants.TOTAL_COIN > 9999) {
            btnCoin.getLayoutParams().width = (int) Tools.convertDpToPx(66, this);
        } else if (Constants.TOTAL_COIN > 999) {
            btnCoin.getLayoutParams().width = (int) Tools.convertDpToPx(58, this);
        }
        countCoin();
    }
    //统计金币总数
    private void countCoin(){
        if(Constants.TOTAL_COIN<10){
            MobclickAgent.onEvent(GameActivity.this, "coins_less_10");
        }else if(Constants.TOTAL_COIN<20){
            MobclickAgent.onEvent(GameActivity.this, "coins_less_20");
        }else if(Constants.TOTAL_COIN<50){
            MobclickAgent.onEvent(GameActivity.this, "coins_less_50");
        }else if(Constants.TOTAL_COIN<100){
            MobclickAgent.onEvent(GameActivity.this, "coins_less_100");
        }else if(Constants.TOTAL_COIN<200){
            MobclickAgent.onEvent(GameActivity.this, "coins_less_200");
        }else if(Constants.TOTAL_COIN<500){
            MobclickAgent.onEvent(GameActivity.this, "coins_less_500");
        }else if(Constants.TOTAL_COIN<1000){
            MobclickAgent.onEvent(GameActivity.this, "coins_less_1000");
        }else if(Constants.TOTAL_COIN<2000){
            MobclickAgent.onEvent(GameActivity.this, "coins_less_2000");
        }else{
            MobclickAgent.onEvent(GameActivity.this, "coins_less_max");
        }
    }

    private void initButtons() {
        //初始化第一行按钮
        answerButtonOne = (Button) findViewById(R.id.game_answerone);
        answerButtonTwo = (Button) findViewById(R.id.game_answertwo);
        answerButtonThree = (Button) findViewById(R.id.game_answerthree);
        answerButtonFour = (Button) findViewById(R.id.game_answerfour);
        answerButtonFive = (Button) findViewById(R.id.game_answerFive);
        answerButtonSix = (Button) findViewById(R.id.game_answerSix);
        answerButtonSeven = (Button) findViewById(R.id.game_answerSeven);
        answerButtonEight = (Button) findViewById(R.id.game_answerEight);
        answerButtonNine = (Button) findViewById(R.id.game_answerNine);
        answerButtonTen = (Button) findViewById(R.id.game_answerTen);

        answerButtons = new ArrayList<>();
        answerButtons.add(answerButtonOne);
        answerButtons.add(answerButtonTwo);
        answerButtons.add(answerButtonThree);
        answerButtons.add(answerButtonFour);
        answerButtons.add(answerButtonFive);
        answerButtons.add(answerButtonSix);
        answerButtons.add(answerButtonSeven);
        answerButtons.add(answerButtonEight);
        answerButtons.add(answerButtonNine);
        answerButtons.add(answerButtonTen);

        //初始化第二行按钮
        answerButtonOne2 = (Button) findViewById(R.id.game_answerone2);
        answerButtonTwo2 = (Button) findViewById(R.id.game_answertwo2);
        answerButtonThree2 = (Button) findViewById(R.id.game_answerthree2);
        answerButtonFour2 = (Button) findViewById(R.id.game_answerfour2);
        answerButtonFive2 = (Button) findViewById(R.id.game_answerFive2);
        answerButtonSix2 = (Button) findViewById(R.id.game_answerSix2);
        answerButtonSeven2 = (Button) findViewById(R.id.game_answerSeven2);
        answerButtonEight2 = (Button) findViewById(R.id.game_answerEight2);
        answerButtonNine2 = (Button) findViewById(R.id.game_answerNine2);
        answerButtonTen2 = (Button) findViewById(R.id.game_answerTen2);

        answerButtons2 = new ArrayList<>();
        answerButtons2.add(answerButtonOne2);
        answerButtons2.add(answerButtonTwo2);
        answerButtons2.add(answerButtonThree2);
        answerButtons2.add(answerButtonFour2);
        answerButtons2.add(answerButtonFive2);
        answerButtons2.add(answerButtonSix2);
        answerButtons2.add(answerButtonSeven2);
        answerButtons2.add(answerButtonEight2);
        answerButtons2.add(answerButtonNine2);
        answerButtons2.add(answerButtonTen2);
    }

    private void initDatabase() {
        db = DbHelper.getDataBase(this);
        if (db != null) {
            String sql = "select * from data;";
            Cursor cursor = db.rawQuery(sql, null);
            String content, answer;
            while (cursor.moveToNext()) {
                answer = cursor.getString(cursor.getColumnIndex("answer"));
                content = cursor.getString(cursor.getColumnIndex("content"));
                correctAnswers.add(answer.trim());
                topics.add(content);
            }

            if (Constants.TOTAL_LEVEL == -1) {
                Constants.TOTAL_LEVEL = correctAnswers.size();
            }
        }
    }

    //获取一个混淆答案
    private String getMixAnswer() {
        int count = correctAnswers.get(Constants.CURRENT_LEVEL).length();//正确答案的长度
        if (count >= Constants.ANSWER_COUNT / 2) {
            return "";
        }
        ArrayList<String> answers = new ArrayList<>();
        ArrayList<String> diffAnswers = new ArrayList<>();

        for (int i = 0; i < correctAnswers.size(); i++) {
            String item = correctAnswers.get(i);
            if (item.length() == count) {
                if (!answers.contains(item)) {
                    answers.add(item);
                }
            }

            if (i != 0 && i != correctAnswers.size() - 1) {
                if (!diffAnswers.contains(item)) {
                    diffAnswers.add(item);
                }
            }
        }
        answers.remove(correctAnswers.get(Constants.CURRENT_LEVEL));
        diffAnswers.remove(correctAnswers.get(Constants.CURRENT_LEVEL));

        if (answers.size() > 0) {//从相同长度的答案里面随机选一个
            int randomIndex = new Random().nextInt(answers.size());
            return answers.get(randomIndex);
        } else {//没有长度一样的就随便选一个不重复的
            return diffAnswers.get(new Random().nextInt(diffAnswers.size()));
        }
    }

    //随机提示一个字母
    public void randomLetter() {
        if (answerWordCount == 2) {//答案有两个单词
            int wordIndex = new Random().nextInt(2);//随机抽取是第一行还是第二行
            int index = new Random().nextInt(answers2[wordIndex].length());
            setAnswerText(index, answers2[wordIndex].substring(index, index + 1), wordIndex == 1);

            hideLetter(index + wordIndex * answers2[0].length(), answers2[wordIndex].substring(index, index + 1));
        } else {//一个单词
            String answer = correctAnswers.get(Constants.CURRENT_LEVEL);
            int index = new Random().nextInt(answer.length());
            setAnswerText(index, answer.substring(index, index + 1), false);

            hideLetter(index, answer.substring(index, index + 1));
        }

        Constants.TOTAL_COIN -= Constants.COINS_COST_RANDOM_LETTER;
        refreshCoin();
        SoundPoolUtils.play(1);
    }

    //随机移除一个字母
    public void removeOneLetter() {
        //这里有逻辑错误，removeIndex得到的是索引的值而非真正的多于列表里的值
//        int removeIndex = new Random().nextInt(getCanRemoveIdList().size());
//        gridview.getChildAt(removeIndex).setVisibility(View.INVISIBLE);
//
//        Constants.TOTAL_COIN -= Constants.COINS_COST_REMOVE_ONE_LETTER;
//        refreshCoin();
//        SoundPoolUtils.play(1);
    }

    //移除全部多余的字母
    public void removeExtraLetters() {
        for (int item : getCanRemoveIdList()) {
            gridview.getChildAt(item).setVisibility(View.INVISIBLE);
        }

        Constants.TOTAL_COIN -= Constants.COINS_COST_REMOVE_EXTRA_LETTERS;
        refreshCoin();
        SoundPoolUtils.play(1);
    }

    //解决问题
    public void solveQuestion(int coinCost) {
        for (int i = 0; i < answerLength; i++) {
            // setAnswerText(i, correctAnswers.get(Constants.CURRENT_LEVEL).substring(i, i + 1), false);
            if (answerWordCount == 2 && i >= answers2[0].length()) {//第二行
                setAnswerText(i - answers2[0].length(), correctAnswers.get(Constants.CURRENT_LEVEL).replace(" ", "").substring(i, i + 1), true);
            } else {//一行
                setAnswerText(i, correctAnswers.get(Constants.CURRENT_LEVEL).replace(" ", "").substring(i, i + 1), false);
            }
        }

//                        setAnswerText(0, correctAnswers.get(Constants.CURRENT_LEVEL));
        addCoin(-coinCost);

        Constants.CHECK_ANSWER_COUNT++;
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("check_answer_count", Constants.CHECK_ANSWER_COUNT);
        editor.apply();
    }

    //获取可以移除的datalist索引列表
    private ArrayList<Integer> getCanRemoveIdList() {
        ArrayList<Integer> result = new ArrayList<>();

        ArrayList<String> answerWords = new ArrayList<>();
        String answer = correctAnswers.get(Constants.CURRENT_LEVEL);
        for (int i = 0; i < answer.length(); i++) {
            if (!answer.substring(i, i + 1).equals(" ")) {
                answerWords.add(answer.substring(i, i + 1));
            }
        }

        for (int i = 0; i < datalist.size(); i++) {
            if (answerWords.contains(datalist.get(i))) {
                answerWords.remove(datalist.get(i));
            } else {
                result.add(i);
            }
        }

        return result;
    }

    //从GridView里隐藏一个指定的字母
    private void hideLetter(int index, String letter) {
        for (int i = 0; i < datalist.size(); i++) {
            if (datalist.get(i).equals(letter)) {
                views[index] = gridview.getChildAt(i);//让点击答案框的时候这个view可以回到gridview里去
                gridview.getChildAt(i).setVisibility(View.INVISIBLE);
                break;
            }
        }
    }

    private void setShareContent() {
        // APP ID:1104684538 APP KEY:pMFpe54excoUzfBF
//        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(MainActivity.this, "1104684538", "pMFpe54excoUzfBF");
//        qZoneSsoHandler.addToSocialSDK();
//        mController.setShareContent("友盟社会化组件（SDK）让移动应用快速整合社交分享功能。http://www.umeng.com/social");

        //设置分享图片，此处分享的图片的URL
        //UMImage urlImage = new UMImage(GameActivity.this, "http://www.umeng.com/images/pic/social/integrated_3.png");

//        UMImage weixinImage=new UMImage(GameActivity.this,R.mipmap.ic_launcher);
//        // 设置微信分享内容
//        WeiXinShareContent weixinContent = new WeiXinShareContent();
//        weixinContent.setShareContent("我正在玩『一句话猜名人』，你知道上面的名言是谁说的吗？来猜猜看吧~");
//        weixinContent.setTitle("七门功课的红灯，照亮我的前程");
//        weixinContent.setTargetUrl("http://shouji.baidu.com/game/9269268.html");
//        weixinContent.setShareMedia(weixinImage);
//        mController.setShareMedia(weixinContent);
//
//        // 设置朋友圈分享的内容
//        CircleShareContent circleMedia = new CircleShareContent();
//        circleMedia.setShareContent("内容");
//        circleMedia.setTitle("\"七门功课的红灯，照亮我的前程\" 猜猜这是谁的名言？");
//        circleMedia.setShareMedia(weixinImage);
//        // circleMedia.setShareMedia(uMusic);
//        // circleMedia.setShareMedia(video);
//        circleMedia.setTargetUrl("http://shouji.baidu.com/game/9269268.html");
//        mController.setShareMedia(circleMedia);

//        UMImage qzoneImage = new UMImage(MainActivity.this, "http://www.umeng.com/images/pic/social/integrated_3.png");
//        qzoneImage.setTargetUrl("http://www.umeng.com/images/pic/social/integrated_3.png");

        // 设置QQ空间分享内容
//        QZoneShareContent qzone = new QZoneShareContent();
//        qzone.setShareContent("share test");
//        qzone.setTargetUrl("http://www.umeng.com");
//        qzone.setTitle("QZone title");
//        qzone.setShareMedia(urlImage);
//        // qzone.setShareMedia(uMusic);
//        mController.setShareMedia(qzone);

        //设置ＱＱ的分享图片，此处分享的是本地资源图片
//		UMImage image = new UMImage(MainActivity.this, BitmapFactory.decodeResource(getResources(), R.drawable.share));
//		image.setTitle("thumb title");
//		image.setThumb("http://www.umeng.com/images/pic/social/integrated_3.png");
//
//		// 设置ＱＱ分享内容
//		QQShareContent qqShareContent = new QQShareContent();
//		qqShareContent.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能 -- QQ");
//		qqShareContent.setTitle("hello, title");
//		qqShareContent.setShareMedia(image);
//		qqShareContent.setTargetUrl("http://www.umeng.com/social");
//		mController.setShareMedia(qqShareContent);

        //新浪微博分享注意：
        // 1. 需要在新浪平台填写包名和签名
        // 2.  在友盟http://www.umeng.com/apps配置在新浪平台注册的App Key和App Secret
        // 3. 在新浪平台 ==> 我的应用==》应用信息 ==》高级信息 ==》OAuth2.0 授权设置 编辑 设置新浪的授权回调页面https://api.weibo.com/oauth2/default.html
        // 4. 在新浪平台注册应用基本信息安全域名设置这个sns.whalecloud.com
        // App Key：2229550199　　　　App Secret：6b7a1c5abfe7aff80c5112ef0f56d3fb
//        SinaShareContent sinaContent = new SinaShareContent();
//        sinaContent.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能-新浪微博。http://www.umeng.com/social");
//        mController.setShareMedia(sinaContent);
    }

    //初始化分享平台
    private void initSharePlatform() {
//        PlatformConfig.setWeixin(Constants.WX_APP_ID, Constants.WX_APP_SECRET);
//        PlatformConfig.setSinaWeibo("2794502943", "b5e5ed8584940c27c2a109505637e4cb");
//        PlatformConfig.setQQZone("1105345528", "WNjd8Rv7il8ZwJN2");//QQ和QQ空间
    }

    //分享到各个平台
    private void shareToPlatforms() {

        //微信好友
//        ShareContent weixinContent = new ShareContent();
//        weixinContent.mMedia = new UMImage(GameActivity.this, R.mipmap.ic_launcher);
//        weixinContent.mText = "我正在玩『一句话猜名人』，你知道上面的名言是谁说的吗？来猜猜看吧~";
//        weixinContent.mTitle = getCurrentTopic();
//        weixinContent.mTargetUrl = "http://app.qq.com/#id=detail&appid=1105345528";
//
//        //朋友圈
//        ShareContent circleContent = new ShareContent();
//        circleContent.mMedia = new UMImage(GameActivity.this, R.mipmap.ic_launcher);
//        circleContent.mText = "一句话猜名人内容";
//        circleContent.mTitle = "\"" + getCurrentTopic() + "\"  猜猜这是谁的名言？";
//        circleContent.mTargetUrl = "http://app.qq.com/#id=detail&appid=1105345528";
//
//        //新浪微博
//        ShareContent weiboContent = new ShareContent();
////        weiboContent.mMedia=new UMImage(GameActivity.this,R.mipmap.ic_launcher);
//        weiboContent.mMedia = new UMImage(GameActivity.this, getScreenShot(GameActivity.this));
//        weiboContent.mText = "\"" + getCurrentTopic() + "\"  你知道上面的名言是谁说的吗？一句话猜名人,来猜猜看吧~";
//        weiboContent.mTitle = "来自『一句话猜名人』";
////        weiboContent.mTargetUrl="http://shouji.baidu.com/game/9269268.html";
//        weiboContent.mTargetUrl = "http://app.qq.com/#id=detail&appid=1105345528";
//
//        //QQ
//        ShareContent qqContent = new ShareContent();
//        qqContent.mMedia = new UMImage(GameActivity.this, R.mipmap.ic_launcher);
//        qqContent.mText = "一句话猜名人，知道这是谁的名言么？";
//        qqContent.mTitle = getCurrentTopic();
//        qqContent.mTargetUrl = "http://app.qq.com/#id=detail&appid=1105345528";
//
//        //QQ空间
//        ShareContent qqZoneContent = new ShareContent();
//        qqZoneContent.mMedia = new UMImage(GameActivity.this, R.mipmap.ic_launcher);
//        qqZoneContent.mText = "我正在玩『一句话猜名人』，你知道上面的名言是谁说的吗？来猜猜看吧~";
//        qqZoneContent.mTitle = getCurrentTopic();
//        qqZoneContent.mTargetUrl = "http://app.qq.com/#id=detail&appid=1105345528";
//
//        //分享
//        new ShareAction(this).setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)
//                .setContentList(weixinContent, circleContent, weiboContent, qqContent, qqZoneContent)
//                .open();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    //获取屏幕截图
    public Bitmap getScreenShot(Activity activity) {
        // 获取windows中最顶层的view
        View view = activity.getWindow().getDecorView();
        view.buildDrawingCache();

        // 获取状态栏高度
        Rect rect = new Rect();
        view.getWindowVisibleDisplayFrame(rect);
        int statusBarHeights = rect.top;
        Display display = activity.getWindowManager().getDefaultDisplay();

        // 获取屏幕宽和高
        int widths = display.getWidth();
        int heights = display.getHeight();

        // 允许当前窗口保存缓存信息
        view.setDrawingCacheEnabled(true);

        // 去掉状态栏
        Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0,
                statusBarHeights, widths, heights - statusBarHeights);

        // 销毁缓存信息
        view.destroyDrawingCache();

        return bmp;
    }

    //领取Watch Video的奖励
    private void getWatchVideoCoins() {
        if (Constants.rewardedVideoAd.isLoaded()) {
            Constants.rewardedVideoAd.show();
            UMGameAgent.bonus("Watch Video_earn", 1, Constants.COINS_EARN_WATCH_VIDEO, 3);
            MobclickAgent.onEvent(GameActivity.this, "watch_video_from_game");
        } else {
            mIsRewardedVideoLoading = false;
            loadRewardedVideoAd();
            if (Constants.rewardedVideoAd.isLoaded()) {
                Constants.rewardedVideoAd.show();
            } else {
                Toast.makeText(this, R.string.no_video_hint, Toast.LENGTH_SHORT).show();
            }
        }
    }

    //加载视频激励广告
    private void loadRewardedVideoAd() {
        synchronized (mLock) {
            if (!mIsRewardedVideoLoading) {
                mIsRewardedVideoLoading = true;
                Bundle extras = new Bundle();
                extras.putBoolean("_noRefresh", true);
                AdRequest adRequest = new AdRequest.Builder()
                        .addNetworkExtrasBundle(AdMobAdapter.class, extras)
                        .build();
                Constants.rewardedVideoAd.loadAd(getString(R.string.rewarded_ad_unit_id), adRequest);
            }
        }
    }

    //视频激励广告的回调
    @Override
    public void onRewardedVideoAdLoaded() {
        synchronized (mLock) {
            mIsRewardedVideoLoading = false;
        }
        imageVideo.setVisibility(View.VISIBLE);
    }

    @Override
    public void onRewardedVideoAdOpened() {

    }

    @Override
    public void onRewardedVideoStarted() {

    }

    @Override
    public void onRewardedVideoAdClosed() {
//        if (!Constants.rewardedVideoAd.isLoaded()) {
//            loadRewardedVideoAd();
//        }
        if (!Constants.rewardedVideoAd.isLoaded()) {
            loadRewardedVideoAd();
            imageVideo.setVisibility(View.INVISIBLE);
        } else {
            imageVideo.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onRewarded(RewardItem rewardItem) {
        handleCoin(Constants.COINS_EARN_WATCH_VIDEO);
    }

    @Override
    public void onRewardedVideoAdLeftApplication() {

    }

    @Override
    public void onRewardedVideoAdFailedToLoad(int i) {
        imageVideo.setVisibility(View.INVISIBLE);
        synchronized (mLock) {
            mIsRewardedVideoLoading = false;
        }
        loadRewardedVideoAd();
    }

    //处理领取奖励之后的金币问题
    private void handleCoin(int coins) {
        Constants.TOTAL_COIN += coins;
        refreshCoin();

        SoundPoolUtils.play(1);
        Toast.makeText(GameActivity.this, getString(R.string.get_coins_hint) + coins, Toast.LENGTH_LONG).show();

    }
}
